import _ from 'underscore';
import React from 'react';
import Card from 'lib/components/card.jsx';
import { defaultApi, defaultPostApi } from '../../apis/core-util';
import GridWidget from 'lib/components/GridWidget.jsx';
import ReactPages from 'react-pagers';
import { Link } from 'react-router';
import Loading from 'lib/util/defaultLoadingElement.jsx';
import query from 'lib/util/QueryStore.es6';

class UserSerializationView extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      data: [],
      loading: true,
      columns: [],
      count: 0,
      active: 1,
      pageTotal: 1
    };

    this.downloadArgs = {
      parameters: null,
      profile: null
    };

    this.pageSize = 50;

    this.propertyApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/property/user/properties`
    });

    this.api = defaultPostApi({
      __url: `sd/${ BlueWare.appId }/api/events/user/list`
    });

    let parameters = query.get();

    parameters.slice_by_values = _.map(parameters.slice_by_values, (item) => {
      return item === '' ? null : item;
    }) || [];

    this.parameters = parameters;
  }

  reload() {
    this.setState({
      loading: true
    });

    this.fetch();
  }

  getParams(pageSize) {
    let parameters = _.extend({}, this.parameters, {
      page: this.state.active - 1,
      num_per_page: pageSize || this.pageSize,
      request_id: new Date().getTime()
    });

    return parameters;
  }

  fetch() {
    this.api.post(config => {
      config.data = JSON.stringify(this.getParams());
      config.contentType = 'application/json';

      return config;
    })
    .then((response) => {

      this.state.data = _.map(response.users, (user) => {
        return {
          first_id: user.first_id,
          distinct_id: user.second_id ? user.second_id : user.first_id,
          profiles: user.profiles,
          id: user.id
        };
      });

      this.state.count = response.size;
      this.state.pageTotal = response.page_num;

      this.propertyApi
        .fetch()
        .then((res) => {
          let columns = _.map(response.column_name, (column_name, index) => {
            let result = _.find(res, (item) => {
              return item.name === column_name;
            });
            return {
              key: column_name,
              title: <span data-tip={ result.cname }>{result.cname}</span>,
              sortable: true,
              render: (fmtVal, {profiles}) => {
                if (_.isArray(profiles[column_name])) {
                  return <span data-tip={profiles[column_name].join(', ')}>{ profiles[column_name].join(', ') }</span>
                }

                return <span>{ _.isNull(profiles[column_name]) ? '-' : profiles[column_name] }</span>
              }
            };
          });
          this.state.columns = [
            {
              title: <span data-tip="distinct_id">distinct_id</span>,
              key: 'distinct_id',
              sortable: true,
              render: (fmtVal, user) => {
                return <Link to={`/users/sequence/${user.id}${this.props.location.search}`} onClick={ this.handleLinkClicked.bind(this, user) }>{ fmtVal }</Link>
              }
            },
            ...columns
          ];
        }).always(() => {
          this.setState({
            loading: false
          });
        });
    });
  }

  handleLinkClicked(user) {
    if (window.sessionStorage) {
      sessionStorage.setItem('sequence-user', JSON.stringify(user));
    }
  }

  download() {
    this.refs.download.submit();
  }

  componentWillMount() {
    this.fetch();
  }

  handlePagination(active) {
    this.state.active = active;
    this.reload();
  }

  handleClose() {
    this.props.history.pushState(null, '/');
  }

  render() {
    let store = {
          data: this.state.data
        },
        {
          from_date,
          to_date
        } = this.parameters;

    return (
      <div className="box event-users">
        <div className="widget-float position-relative">
          <div className="widget-tools">
            <a className="iconfont icon-refresh" href="javascript:;" onClick={ this.reload.bind(this) }></a>
            <a className="iconfont icon-download" href="javascript:;" onClick={ this.download.bind(this) }></a>
          </div>
          <div className="widget-title">
            <a className="close iconfont" href="javascript:;" onClick={ this.handleClose.bind(this) }>&#xe638;</a>
            <h4>用户列表</h4>
          </div>
          <div className="widget-content">
            <div className="pure-g">
              <div className="pure-u-1">
                <div className="box">
                  <div className="widget-normal">
                    {
                      this.state.loading ? <Loading /> : (
                        <div>
                          <div className="event-users-list">
                            <GridWidget store={ store } cols={ this.state.columns } />
                          </div>
                          <div className="paginator clearfix">
                            <div className="page-info">
                              共 { this.state.count } 行，当前显示 { (this.state.active - 1) * this.pageSize + 1 }-{ store.data.length < this.pageSize ? store.data.length : this.state.active * this.pageSize } 行
                            </div>
                            <ReactPages useHash={ false } onChange={ this.handlePagination.bind(this) } active={ this.state.active } total={ this.state.pageTotal } jumper={ true } />
                          </div>
                        </div>
                      )
                    }
                  </div>
                </div>
                <form
                  action={ `/mobile/sd/${ BlueWare.appId }/api/events/user/list/csv` }
                  ref="download"
                  style={{display: 'none'}}
                  acceptCharset="UTF-8"
                  encType="application/x-www-form-urlencoded"
                  target="_blank"
                  method="POST">
                  <input name="filename" type="hidden" value={`行为事件分析-用户列表-${from_date}至${to_date}`} />
                  <input name="form_data" type="hidden" value={ JSON.stringify(this.getParams(this.state.count)) } />
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

UserSerializationView.defaultProps = {
  queries: ''
};

export default UserSerializationView
